package com.mysqlpass.update.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;

/**
 * 静态文件控制器，用于提供MySQLPass的静态下载页面
 */
@Controller
@RequestMapping("/update/static")
public class StaticFileController {
    
    private static final Logger logger = Logger.getLogger(StaticFileController.class.getName());
    
    /**
     * 提供mysqlpass_download.html文件下载
     * @return 文件下载响应
     */
    @GetMapping("/mysqlpass_download.html")
    public ResponseEntity<Resource> getDownloadPage(HttpServletRequest request) {
        String clientIp = getClientIp(request);
        logger.info(String.format("[IP: %s] 收到MySQLPass下载页面请求", clientIp));
        
        try {
            // 构建文件路径 - 这里直接使用项目根目录下的mysqlpass_download.html文件
            Path filePath = Paths.get("D:/aiproject/mysqlpass_download.html").normalize();
            logger.info(String.format("[IP: %s] 构建文件路径: %s", clientIp, filePath.toString()));
            
            // 检查文件是否存在和可读
            if (!Files.exists(filePath) || !Files.isReadable(filePath)) {
                logger.warning(String.format("[IP: %s] 文件不存在或不可读: %s", clientIp, filePath.toString()));
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new UrlResource(filePath.toUri());
            long fileSize = Files.size(filePath);
            logger.info(String.format("[IP: %s] 开始提供MySQLPass下载页面: %s (大小: %.2f KB)", 
                    clientIp, filePath.getFileName(), fileSize / 1024.0));
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8")
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileSize))
                    .body(resource);
            
        } catch (MalformedURLException ex) {
            logger.severe(String.format("[IP: %s] 文件URL格式错误: %s", clientIp, ex.getMessage()));
            return ResponseEntity.internalServerError().build();
        } catch (Exception ex) {
            logger.severe(String.format("[IP: %s] 提供MySQLPass下载页面时发生错误: %s", clientIp, ex.getMessage()));
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取客户端IP地址
     * @param request HTTP请求对象
     * @return 客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        
        // 如果有多个IP地址，取第一个
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0].trim();
        }
        
        return ipAddress;
    }
}